package CreationPattern.Singleton;

import java.util.concurrent.CountDownLatch;

/**
 * @Classname : SingletonConcurrencyClient
 * @Description : 测试五种创建单例方式的并发效率
 * @Author : chentianyu
 * @Date 2022/12/26 23:32
 */


public class SingletonConcurrencyClient {
    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();

        int threadNum = 100;
        final CountDownLatch countDownLatch = new CountDownLatch(threadNum);

        for(int i=0; i<threadNum; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for(int j=0; j<1000000; j++){
//                        Object o = CreationPattern.Singleton.getInstance();
//                        Object o2 = Singleton02.getInstance();
//                        Object o3 = Singleton03.getInstance();
//                        Object o4 = Singleton04.getInstance();
                        Object o5 = Singleton05.INSTANCE;
                    }
                    countDownLatch.countDown();
                }  // end run()
            }).start();
        }  // end for
        countDownLatch.await();  //main线程阻塞，直到计数器变为0，才会继续往下执行！

        long end = System.currentTimeMillis();
        System.out.println("总耗时：" + (end-start) + "ms");
    }
}


/** 2022/12/26
 * CreationPattern.Singleton       饿汉式                总耗时：27ms
 * Singleton02     懒汉式-方法加锁同步     总耗时：2738ms
 * Singleton03     懒汉式-双重检查锁       总耗时：40ms
 * Singleton04     静态内部类             总耗时：34ms
 * Singleton05     枚举式                总耗时：24ms
 */